<template>
    <detail-page
        class="research-detail"
        :imgPath="currnetResearch.iconPath"
        :showDeployBtn="true"
        :showCountDown="destroyStatus && deployNum === 3 && proId && leftTime > 0"
        :deployWidth="deployWidth"
        :destroyWidth="destroyWidth"
        :btnType="btnType"
        :destroyTime="leftTime"
        :createdVmText="createdVmText"
        :createdLoad="createdLoad"
        :errorMessage="errorMessage"
        :deployId="deployId"
        :destroyStatus="destroyStatus"
        @on-deploy="deploy"
        @on-destroy="destroy"
    >
        <Tabs v-model="tabName" slot="content-left" class="my-tabs">
            <!-- <TabPane label="科研工具" name="tool">
                <relation-file ref="tool" :type="1" :columns="toolColumns"></relation-file>
            </TabPane> -->
            <!-- <TabPane label="科研课件" name="courseware">
                <relation-file
                    ref="courseware"
                    :type="2"
                    :columns="coursewareColumns"
                ></relation-file>
            </TabPane> -->
            <TabPane label="科研视频" name="video">
                <relation-file ref="video" :type="3" :columns="videoColumns"></relation-file>
            </TabPane>
            <TabPane label="科研文档" name="courseware">
                <relation-file
                    ref="courseware"
                    :type="2"
                    :columns="coursewareColumns"
                ></relation-file>
            </TabPane>
            <TabPane label="科研程序" name="programs">
                <relation-file ref="programs" :type="4" :columns="toolColumns"></relation-file>
            </TabPane>
            <TabPane label="科研分享" name="share">
                <relation-user :currentItem="currnetResearch" ref="share"></relation-user>
            </TabPane>
            <!-- <TabPane label="科研小结" name="summarize">
                <relation-report ref="summarize"></relation-report>
            </TabPane> -->
        </Tabs>
        <div slot="content-text" class="content-text">
            <h3>{{ currnetResearch.name }}</h3>
            <p>
                <span>科研设计师</span>: <span>{{ currnetResearch.accepterName }}</span>
            </p>
            <p>
                <span>设计时间</span>: <span>{{ currnetResearch.createTime }}</span>
            </p>
            <!-- <p>
                <span>方向</span>: <span>{{ handleDirection(currnetResearch.typeCode) }}</span>
            </p> -->
            <p>
                <span>类型</span>: <span>{{ handleCodeType(currnetResearch.typeCode) }}</span>
            </p>
            <p>
                <span>描述</span>: <span>{{ currnetResearch.description }}</span>
            </p>
        </div>
    </detail-page>
</template>
<script>
import encryption from '@/libs/encryption.js';
import { queryContentList } from '@/api/scientific/content';
import {
    deployScientificProject,
    queryDeployProgress,
    queryDestroyTime,
    selectStatus,
    destroyScientificProject,
} from '@/api/scientific/environment';
import { queryProjectstatus } from '@/api/deploy';
import DetailPage from '@/components/detail-page';
import PageLayout from '@/components/common/page';
import RelationFile from '@/view/research/filingList/relation-file';
import RelationReport from '@/view/research/filingList/relation-report';
import RelationUser from '@/view/research/filingList/relation-user';
import typeAndDirectionMixin from '@/mixin/typeAndDirectionMixin.js';
import {mapMutations} from 'vuex'
export default {
    name: 'Detail',
    components: { DetailPage, PageLayout, RelationFile, RelationUser, RelationReport },
    mixins: [typeAndDirectionMixin],
    data() {
        return {
            USER_ID: '',
            currnetResearch: {},
            tabName: 'video',
            toolColumns: [
                {
                    title: '程序名称',
                    key: 'fileName',
                    align: 'center',
                    width: 300,
                    placement: 'top-left',
                    tooltip: true,
                },
                {
                    key: 'action',
                    align: 'center',
                    placement: 'top-right',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                    },
                                    attrs: {
                                        title: '下载',
                                    },
                                    on: {
                                        click: () => {
                                            this.download(params.row);
                                        },
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        color: '#3D52C9',
                                    },
                                },
                                [
                                    // h('Icon', {
                                    //     props: {
                                    //         type: 'md-cloud-download',
                                    //         size: 26
                                    //     }
                                    // })
                                    h('img', {
                                        attrs: {
                                            src: require('../../../assets/mainImage/download-h.png'),
                                        },
                                    }),
                                ]
                            ),
                        ]);
                    },
                },
            ],
            coursewareColumns: [
                {
                    title: '课件名称',
                    key: 'fileName',
                    align: 'center',
                    placement: 'top-left',
                    width: 300,
                    tooltip: true,
                },
                {
                    key: 'action',
                    align: 'center',
                    placement: 'top-right',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                    },
                                    style: {
                                        marginRight: '6px',
                                    },
                                    attrs: {
                                        title: '下载',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        color: '#3D52C9',
                                    },
                                    on: {
                                        click: () => {
                                            this.download(params.row);
                                        },
                                    },
                                },
                                [
                                    // h('Icon', {
                                    //     props: {
                                    //         type: 'md-cloud-download',
                                    //         size: 26
                                    //     }
                                    // })
                                    h('img', {
                                        attrs: {
                                            src: require('../../../assets/mainImage/download-h.png'),
                                        },
                                    }),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                    },
                                    attrs: {
                                        title: '预览',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        color: '#3D52C9',
                                    },
                                    on: {
                                        click: () => {
                                            this.preview(params.row);
                                        },
                                    },
                                },
                                [
                                    // h('Icon', {
                                    //     props: {
                                    //         type: 'md-search',
                                    //         size: 26
                                    //     }
                                    // })
                                    h('img', {
                                        attrs: {
                                            src: require('../../../assets/mainImage/magnifier-h.png'),
                                        },
                                    }),
                                ]
                            ),
                        ]);
                    },
                },
            ],
            videoColumns: [
                {
                    title: '视频名称',
                    key: 'fileName',
                    align: 'center',
                    placement: 'top-left',
                    width: 300,
                    tooltip: true,
                },
                {
                    key: 'action',
                    align: 'center',
                    placement: 'top-right',
                    render: (h, params) => {
                        return h('div', [
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                    },
                                    style: {
                                        marginRight: '6px',
                                    },
                                    attrs: {
                                        title: '下载',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        color: '#3D52C9',
                                    },
                                    on: {
                                        click: () => {
                                            this.download(params.row);
                                        },
                                    },
                                },
                                [
                                    // h('Icon', {
                                    //     props: {
                                    //         type: 'md-cloud-download',
                                    //         size: 26
                                    //     }
                                    // })
                                    h('img', {
                                        attrs: {
                                            src: require('../../../assets/mainImage/download-h.png'),
                                        },
                                    }),
                                ]
                            ),
                            h(
                                'Button',
                                {
                                    props: {
                                        type: 'text',
                                        size: 'small',
                                    },
                                    attrs: {
                                        title: '预览',
                                    },
                                    style: {
                                        border: 'none',
                                        background: 'none',
                                        boxShadow: 'none',
                                        color: '#3D52C9',
                                    },
                                    on: {
                                        click: () => {
                                            this.preview(params.row);
                                        },
                                    },
                                },
                                [
                                    // h('Icon', {
                                    //     props: {
                                    //         type: 'md-search',
                                    //         size: 26
                                    //     }
                                    // })
                                    h('img', {
                                        attrs: {
                                            src: require('../../../assets/mainImage/magnifier-h.png'),
                                        },
                                    }),
                                ]
                            ),
                        ]);
                    },
                },
            ],
            destroyStatus: false,
            deployNum: '', // 部署状态码
            proId: '',
            leftTime: 0, // 自动销毁的时间
            deployWidth: '100%',
            destroyWidth: 'auto',
            btnType: 'primary',
            createdVmText: '创建科研环境',
            createdLoad: false,
            errorMessage: '',
            deployId: '',
        };
    },
    filters: {},
    watch: {
        tabName(newVal) {
            switch (newVal) {
                case 'tool':
                    this.$refs.tool && this.$refs.tool.changePageNow(1);
                    break;
                case 'courseware':
                    this.$refs.courseware && this.$refs.courseware.changePageNow(1);
                    break;
                case 'video':
                    this.$refs.video && this.$refs.video.changePageNow(1);
                    break;
                case 'share':
                    this.$refs.share && this.$refs.share.changePageNow(1);
                    break;
                case 'summarize':
                    this.$refs.summarize && this.$refs.summarize.changePageNow(1);
                    break;
                case 'programs':
                    this.$refs.programs && this.$refs.programs.changePageNow(1);
                    break;
            }
        },
    },
    mounted() {
        let November = sessionStorage.getItem('November');
        November = JSON.parse(encryption.SelfUseDecrypt(November));
        this.USER_ID = November.userId;
        this.$refs.video && this.$refs.video.changePageNow(1);
        this.getResearchDetail();
    },
    methods: {
        ...mapMutations(['addBreadItem']),
        // 点击销毁环境的按钮
        destroy() {
            destroyScientificProject(this.proId)
                .then(({ code, message }) => {
                    if (code == 1) {
                        this.proId = '';
                        this.createdLoad = false;
                        // 创建按钮
                        this.createdVmText = '创建科研环境';
                        this.btnType = 'primary';
                        this.deployWidth = '100%';
                        // 销毁按钮
                        this.destroyStatus = false;
                        this.destroyWidth = '0%';
                        this.$Message.success('销毁成功');
                        this.deployNum = 10;
                        clearInterval(this.destroyInterval);
                        this.errorMessage = '';
                    } else {
                        this.$Message.warning(message);
                    }
                })
                .catch(() => {
                    this.$Message.error('销毁环境异常');
                });
        },
        // 点击部署环境的按钮
        deploy() {
            if (this.deployNum === 3) {
                // 如果已经部署 则进入科研环境
                this.openWebTerminal();
            } else if (this.deployNum === 0 || this.deployNum === 10 || this.deployNum === 6) {
                // 未部署或部署失败
                this.deployExper();
            }
        },
        // 展示虚拟机列表
        openWebTerminal() {
            const { href } = this.$router.resolve({
                path: '/testMachine',
                query: {
                    id: this.currnetResearch.id,
                    projectId: this.proId,
                },
            });
            window.openTrain(href, '_blank');
        },
        // 调用部署接口
        deployExper() {
            this.createdLoad = true;
            if (this.destroyInterval) {
                clearInterval(this.destroyInterval);
            }
            deployScientificProject({
                id: this.currnetResearch.id,
                userId: this.USER_ID,
            })
                .then(({ code, message, data = {} }) => {
                    if (code === 1) {
                        if (data.status && data.status === 3) {
                            this.$Message.info('已有环境部署成功，请先销毁才能部署新的环境');
                            this.createdLoad = false;
                        } else {
                            this.proId = data.projectId;
                            if (this.proId) {
                                this.queryCreatedStatus();
                            }
                        }
                    } else {
                        this.$Message.warning(message);
                        this.createdLoad = false;
                    }
                })
                .catch(() => {
                    this.createdLoad = false;
                    this.$Message.error('部署异常');
                });
        },
        // 查询部署状态
        queryCreatedStatus() {
            this.queryStatus = setInterval(() => {
                queryDeployProgress(this.proId, this.$route.query.id)
                    .then(({ code, message, data = {} }) => {
                        if (code == 1) {
                            this.createdVmText = '部署中...' + data.progress + '%';
                            if (data.progress === 100 && data.status === 3) {
                                this.createdLoad = false;
                                // 创建按钮
                                this.createdVmText = '进入科研环境';
                                this.btnType = 'success';
                                this.deployWidth = '60%';
                                // 销毁按钮
                                this.destroyWidth = '30%';
                                this.destroyStatus = true;
                                this.deployNum = 3;
                                clearInterval(this.queryStatus);
                                this.$Message.success('部署成功');
                                setTimeout(() => {
                                    this.getDestroyTimeInter();
                                }, 3000);
                            } else if (data.progress === 100 && data.status === 6) {
                                this.createdLoad = false;
                                // 按钮颜色 文字
                                this.btnType = 'primary';
                                this.createdVmText = '重新部署';
                                this.deployWidth = '60%';
                                // 显示销毁按钮
                                this.destroyWidth = '30%';
                                this.destroyStatus = true;
                                this.deployNum = 6;
                                this.$Message.warning('部署失败!请销毁后重新部署!');
                                clearInterval(this.queryStatus);
                            }
                        } else {
                            this.createdLoad = false;
                            // 按钮颜色 文字
                            this.btnType = 'primary';
                            this.createdVmText = '重新部署';
                            this.deployWidth = '60%';
                            // 显示销毁按钮
                            this.destroyWidth = '30%';
                            this.destroyStatus = true;
                            this.deployNum = 6;
                            clearInterval(this.queryStatus);
                            this.$Message.warning(message);
                        }
                        this.getProjectInfo(); //查询错误信息
                    })
                    .catch((err) => {
                        this.$Message.error('查询部署状态异常');
                    });
            }, 3000);
        },
        // 获取销毁时间
        getDestroyTimeInter() {
            setTimeout(() => {
                clearInterval(this.destroyInterval);
                this.getDestroyTime();
                //一分钟矫正一次销毁时间
                this.destroyInterval = setInterval(() => {
                    this.getDestroyTime();
                }, 1000 * 60);
            }, 3000);
        },
        // 获取销毁时间
        getDestroyTime() {
            queryDestroyTime(this.proId)
                .then(({ code, data = {} }) => {
                    if (code === 1) {
                        this.leftTime = data.destroyTime;
                        if (this.leftTime > 0) {
                            // 什么操作都不需要做，子组件会自己进行倒计时
                        } else {
                            clearInterval(this.destroyInterval);
                        }
                    }
                })
                .catch((err) => {
                    this.$Message.error('获取销毁时间异常');
                });
        },
        // 获取工程部署错误详情
        getProjectInfo() {
            return new Promise((resolve, reject) => {
                queryProjectstatus(this.proId)
                    .then(({ code, message, attribute = {} }) => {
                        if (code == 1) {
                            this.deployId = attribute.project.deployId;
                            this.errorMessage = attribute.project.errorMessage;
                            if (this.errorMessage) {
                                this.deployWidth = '60%';
                                this.destroyWidth = '30%';
                                this.createdVmText = '重新部署';
                            }
                            if (!this.errorMessage) {
                                resolve();
                            }
                        } else if (code == -2) {
                            this.$Message.error('工程不存在');
                        } else {
                            this.$Message.error(message);
                        }
                    })
                    .catch((error) => {
                        this.$Message.error('获取工程部署详情异常');
                    });
            });
        },
        // 下载文件
        download(item) {
            let a = document.createElement('a');
            let fileName = item.fileName; //filename名称截取
            a.href = `/api/minio/download?path=${item.path}`;
            a.download = fileName; //命名下载名称
            a.click(); //点击触发下载
        },
        // 预览文件
        preview(item) {
            window.openTrain(`/api/minio/filePreview?path=${item.path}`);
        },
        // 返回列表页
        returnExper() {
            this.$router.push({
                name: 'researchList',
            });
        },
        // 获取详情信息
        getResearchDetail() {
            queryContentList({ id: this.$route.query.id })
                .then(({ code, message, data = {} }) => {
                    if (code !== 1) {
                        this.$Message.warning(message);
                        return;
                    }
                    this.currnetResearch = (data.items && data.items[0]) || [];
                    this.addBreadItem({ name: this.currnetResearch.name });
                })
                .catch(() => {
                    this.$Message.error('分享项目异常');
                });
            selectStatus(this.$route.query.id)
                .then(({ code, message, data = {} }) => {
                    if (code === 1) {
                        let status = data.deployStatus;
                        this.deployNum = data.deployStatus || 0;
                        this.proId = data.projectId;
                        //查询工程详情
                        if (this.proId) {
                            this.getProjectInfo(false);
                        }
                        // 新建   未部署
                        if (status === 0 || status === 10) {
                            // 按钮颜色 文字
                            this.btnType = 'primary';
                            this.deployWidth = '100%';
                            this.createdVmText = '创建科研环境';
                        } else if (status === 3) {
                            // 成功
                            // 按钮颜色 文字
                            this.btnType = 'success';
                            this.createdVmText = '进入科研环境';
                            this.deployWidth = '60%';
                            // 显示销毁按钮
                            this.destroyWidth = '30%';
                            this.destroyStatus = true;
                            this.getDestroyTimeInter();
                        } else if (status === 6) {
                            // 失败
                            // 按钮颜色 文字
                            this.btnType = 'primary';
                            this.createdVmText = '重新部署';
                            this.deployWidth = '60%';
                            // 显示销毁按钮
                            this.destroyWidth = '30%';
                            this.destroyStatus = true;
                            this.$Message.error({
                                content: '部署失败!请销毁后重新部署!',
                                duration: 10,
                            });
                        } else if (status === 9) {
                            // 部署中
                            this.btnType = 'primary';
                            this.createdVmText = '部署中...';
                            this.deployWidth = '100%';
                            this.createdLoad = true;
                            this.queryCreatedStatus();
                        }
                    } else {
                        this.$Message.warning(message);
                    }
                })
                .catch(() => {
                    this.$Message.error('查询当前设计师科研部署状态异常');
                });
        },
    },
    beforeDestroy() {
        clearInterval(this.queryStatus);
        clearTimeout(this.destroyInterval);
    },
};
</script>
<style scoped>
.research-detail {
    /* padding: 30px; */
}
.my-tabs /deep/ .ivu-tabs-ink-bar {
    z-index: unset !important;
}

.research-detail /deep/ .ivu-tabs {
    height: 100%;
}

.research-detail /deep/ .ivu-tabs-tab {
    font-size: 16px;
    margin-bottom: 20px;
}

.research-detail /deep/ .ivu-tabs-content {
    height: calc(100% - 68px);
}

.research-detail /deep/ .ivu-tabs-tab-active {
    font-size: 22px;
    font-weight: 600;
    color: #333333;
}

.research-detail /deep/ .ivu-tabs-tabpane {
    padding: 0 30px;
    height: 100%;
}

.navigation-bars {
    color: rgb(27, 76, 184);
}

.addressIcon {
    display: inline-block;
    height: 14px;
    width: 12px;
    background: url('../../../assets/globalIcon/addressIcon.png') no-repeat center;
    background-size: 100% 100%;
    margin-bottom: -1px;
}

.content-text {
    width: 100%;
}

.content-text > h3 {
    margin-bottom: 10px;
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: keep-all;
}

.content-text > p {
    color: #a9a9a9;
    display: flex;
}

.content-text > p > span:first-child {
    width: 80px;
    display: inline-block;
    text-align: justify;
    height: 20px;
}

.content-text > p > span:first-child::after {
    width: 100%;
    content: '';
    display: inline-block;
}

.content-text > p > span:last-child {
    width: calc(100% - 90px);
    margin-left: 10px;
    display: inline-block;
    word-break: break-word;
}
</style>
